package user

import (
	"easy-sys/base/dao"
	"easy-sys/base/entity"
	"github.com/jinzhu/gorm"
)

func List(sysUser SysUser, page entity.EasyPage) entity.EasyPage {
	var users []SysUser
	dao.Db.Where(sysUser).Limit(page.PageSize()).Offset(page.PageOffset()).Select("user_id, user_name, user_status, user_mobile, user_email, update_time, update_by, create_by, create_time").Find(&users)
	page.Records = users
	var total int
	dao.Db.Model(&SysUser{}).Where(sysUser).Count(&total)
	page.Total = total
	return page
}

func FindOneByUser(sysUser SysUser) SysUser {
	var users SysUser
	dao.Db.Where(sysUser).First(&users)
	return users
}

func GetUserByRoleId(sysUser SysUser, roleId uint64, page entity.EasyPage) entity.EasyPage {
	var users []SysUser
	dao.Db.Joins("JOIN sys_user_role ru ON ru.user_id = sys_user.user_id and ru.role_id  = ?", roleId).Where(sysUser).Limit(page.PageSize()).Offset(page.PageOffset()).Find(&users)
	page.Records = users
	var total int
	dao.Db.Model(&SysUser{}).Joins("JOIN sys_user_role ru ON ru.user_id = sys_user.user_id and ru.role_id  = ?", roleId).Where(sysUser).Count(&total)
	page.Total = total
	return page
}

func Save(sysUser SysUser) int64 {
	var db *gorm.DB
	if sysUser.UserId ==0 {
		db = dao.Db.Create(&sysUser)
	}else {
		db = dao.Db.Model(&sysUser).Where("user_id = ?", sysUser.UserId).Update(&sysUser)
	}
	return db.RowsAffected
}

func Delete(sysUser SysUser) int64 {
	var db *gorm.DB
	if sysUser.UserId != 0 {
		db = dao.Db.Where("user_id = ?", sysUser.UserId).Delete(&sysUser)
	}
	return db.RowsAffected
}
